<?php

namespace addons\Flow\merchant\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use common\models\common\Menu;
use common\models\base\SearchModel;
use common\traits\Curd;
use addons\Flow\common\models\Workflow;
use addons\Flow\common\models\Metadata;
use addons\Flow\common\models\Status;
use addons\Flow\common\models\Transition;

/**
 * 管理
 *
 * Class NoticeController
 * @package addons\RfNotice\backend\controllers
 * @author YiiFrame <21931118@qq.com>
 */
class WorkflowController extends BaseController
{
    use Curd;

    public $modelClass = Workflow::class;

    public function actionIndex()
    {

        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['merchant' => ['company_name']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['title', 'merchant.company_name'], // 模糊查询
            'defaultOrder' => [
                'merchant_id' => SORT_DESC,
                'sort' => SORT_ASC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere([Workflow::tableName() . '.merchant_id' => $this->getMerchantId()]);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    public function actionAll()
    {

        $searchModel = new SearchModel([
            'model' => Menu::class,
            'scenario' => 'default',
            'defaultOrder' => [
                'sort' => SORT_ASC
            ],
            'pageSize' => $this->pageSize
        ]);

        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andFilterWhere(['like', 'url', '/office/approve/']);

        return $this->render($this->action->id, [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
        ]);
    }

    /**
     * 编辑/创建
     */
    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', null);
        $model = $this->findModel($id);
        $model->merchant_id = Yii::$app->user->identity->merchant_id;

        if ($model->load($request->post()) && $model->save()) {

            return $this->redirect(['index']);
        }

        return $this->render($this->action->id, [
            'model' => $model,
            'workflow_id' => $id,
        ]);
    }

    public function actionAjaxEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $model = $this->findModel($id);
        $model->merchant_id = Yii::$app->user->identity->merchant_id;
        $this->activeFormValidate($model);
        if ($model->load(Yii::$app->request->post())) {
            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
            'workflow_id' => $id,
        ]);
    }

    /**
     * 删除
     */
    public function actionDelete($id)
    {
        // 事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            Workflow::deleteAll(['id' => $id, 'merchant_id' => Yii::$app->user->identity->merchant_id]);
            Status::deleteAll(['workflow_id' => $id, 'merchant_id' => Yii::$app->user->identity->merchant_id]);
            Transition::deleteAll(['workflow_id' => $id, 'merchant_id' => Yii::$app->user->identity->merchant_id]);
            Metadata::deleteAll(['workflow_id' => $id, 'merchant_id' => Yii::$app->user->identity->merchant_id]);
//            Repair::deleteAll(['workflow_id' => $id, 'merchant_id' => Yii::$app->user->identity->merchant_id]);
            $transaction->commit();
            return $this->message("删除成功", $this->redirect(['index']));
        } catch (\Exception $e) {
            $transaction->rollBack();
            return (Yii::$app->request->referrer);
        }

//        if ($this->findModel($id)->delete()) {
//
//            return $this->message("删除成功", $this->redirect(['index']));
//        }

    }

    public function actionInstall()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        // 事务
        $transaction = Yii::$app->db->beginTransaction();
        try {
            //安装流程
            $model = $this->findModel($id);
            $model->merchant_id = Yii::$app->user->identity->merchant_id;
            $model->title = $request->get('title');
            $model->id = $request->get('id');
            $model->initial_status_id = 'apply';
            if (!$model->save()) {
                throw new NotFoundHttpException('安装流程失败');
            }
            //初始化流程状态
            $list = ['apply' => '申请', 'audit' => '审核', 'approve' => '审批', 'refused' => '拒绝'];
            foreach ($list as $id => $label) {
                $status = new Status();
                $status->workflow_id = Yii::$app->request->get('id');
                $status->merchant_id = Yii::$app->user->identity->merchant_id;
                $status->label = $label;
                $status->id = $id;
                if (!$status->save()) {
                    throw new NotFoundHttpException('初始化流程状态失败');
                }
            }
            //初始化工作流转
            $list = ['apply/audit', 'apply/refused', 'audit/approve', 'audit/refused'];
            foreach ($list as $value) {
                $transition = new Transition();
                $transition->workflow_id = Yii::$app->request->get('id');
                $transition->merchant_id = Yii::$app->user->identity->merchant_id;
                $transition->start_status_id = explode('/', $value)[0];;
                $transition->end_status_id = explode('/', $value)[1];
                if (!$transition->save()) {
                    throw new NotFoundHttpException('初始化工作流转失败');
                }
            }

            $transaction->commit();
            return $this->message("安装成功", $this->redirect(['index']));
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->message("安装失败", $this->redirect(['workflow/index']));
        }

        return $this->renderAjax($this->action->id, [
            'model' => $model,
            'workflow_id' => $id,
        ]);
    }

    protected function findModel($id)
    {
        if (empty($id) || empty(($model = $this->modelClass::find()->andWhere(['id' => $id, 'merchant_id' => $this->getMerchantId()])->one()))) {
            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }
        return $model;
    }


}